from flask_login import current_user
from flask import request, jsonify, current_app, session
from functools import wraps
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_v1_5, DES
from Cryptodome.Random import get_random_bytes
from Cryptodome.Util.Padding import pad
from base64 import b64decode
from datetime import datetime
from Common.BaseModel import db
from binascii import b2a_base64, a2b_base64, b2a_hex


# 数据结果对象转为字典
def instance_to_dict(instance_obj):
    instance_dict = {}
    for (key, val) in instance_obj.__dict__.items():
        if key == '_sa_instance_state':
            continue
        if isinstance(val, list):
            continue
        if isinstance(val, db.Model):
            continue
        if isinstance(val, datetime):
            instance_dict[key] = val.strftime('%Y-%m-%d %H:%M:%S')
        else:
            instance_dict[key] = val
    return instance_dict


# 授权检查
def check_permission(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        try:
            reqMethod = request.method
            reqPath = request.path[4:]
            reqScope = None
            if reqMethod == 'GET' or reqMethod == 'DELETE':
                reqScope = request.args.get('scope')
            else:
                reqScope = request.json['scope']
            user_roles = current_user.roles
            for role in user_roles:
                for action in role.actions:
                    if action.api == reqPath and action.method == reqMethod and action.scope == reqScope:
                        return func(*args, **kwargs)
            return jsonify({'code': '0x00021', 'msg': '没有权限'})
        except Exception as error:
            print('权限检查装饰器出错：%s' % error)
    return decorated_view


# RSA生成key
def generate_raskey():
    key = RSA.generate(1024)
    session['pubkey'] = key.publickey().export_key()
    session['prikey'] = key.export_key()


# RSA解密
def rsa_decrypt(ciphertext):
    key = RSA.import_key(session.get('prikey'))
    cipher_rsa = PKCS1_v1_5.new(key)
    return cipher_rsa.decrypt(b64decode(ciphertext), None).decode()


# RSA加密
def rsa_encrypt(plaintext):
    key = RSA.import_key(session.get('pubkey'))
    cipher_rsa = PKCS1_v1_5.new(key)
    raw_data = plaintext.encode()
    return cipher_rsa.encrypt(raw_data, None)


# DES生成key
def generate_deskey():
    session['secret'] = b2a_base64(get_random_bytes(8), newline=False).decode()


# DES加密
def des_encrypt(plaintext):
    try:
        des_key = a2b_base64(session.get('secret'))
        des_ins = DES.new(des_key, DES.MODE_ECB)
        enc_data = des_ins.encrypt(pad(plaintext.encode(), 8))
        hex_data = b2a_hex(enc_data).decode()
        return hex_data
    except Exception as error:
        print('数据加密错误：%s' % error)


def des_decrypt(ciphertext):
    pass


# DES解密
